#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:manage.py
# author:JackieX
# datetime:2022-02-06 14:28
# software: PyCharm

"""
   应用启动的入口程序
"""

from app import create_app
from flask_script import Manager, Server
from flask import request, g, jsonify
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from app.utils.response_code import RET
from app.utils.loggings import loggings
# 创建flask的app对象(利用工厂模式);
# 创建对象时，传入此时配置环境参数：develop;


app = create_app("product")
manager = Manager(app)
manager.add_command("runserver", Server(use_debugger=True, port=8000))


@app.before_request
def user_validation():
    print(request.endpoint)  # 方便跟踪调试

    if not request.endpoint:  # 如果请求点为空
        return jsonify(code=RET.NOTFOUND, message="url not found", error="url not found")

    # 请求点白名单
    permission = ["ssoUser.user_login", "apiversion.apiversion", "ssoUser.ssoUser"]

    # 如果不是请求上述列表中的接口，需要验证token
    if request.endpoint not in permission:
        # 在请求头上拿到token
        token = request.headers.get("Token")
        if not all([token]):
            return jsonify(code=RET.PARAMERR, message="缺少参数Token或请求非法")

        # 校验token格式正确与过期时间
        s = Serializer(app.config["SECRET_KEY"])
        try:
            g.user = s.loads(token)
        except Exception as e:
            loggings.exception(1, e)
            # 单平台用户登录失效
            return jsonify(code=RET.SESSIONERR, message='用户未登录或登录已过期')


@app.after_request
def check_status_code(response):
    from flask import jsonify
    # 捕获flask_limiter的频率限制返回,ratelimit暂时无法捕获
    if response.status == '429 TOO MANY REQUESTS':
        response = {"code": RET.REQERR, "error": "该ip一定时间内请求过多,暂时拒绝访问", "message": "该ip一定时间内请求过多,暂时拒绝访问"}
        response = jsonify(response)
        print(response)

    return response


# 创建全站拦截器，每个请求之后根据请求方法统一设置返回头
@app.after_request
def process_response(response):
    allow_cors = ['OPTIONS', 'PUT', 'DELETE', 'GET', 'POST']
    if request.method in allow_cors:
        response.headers["Access-Control-Allow-Origin"] = '*'
        if request.headers.get('Origin') and request.headers['Origin'] == 'http://127.0.0.1':
            response.headers["Access-Control-Allow-Origin"] = 'http://127.0.0.1:5000'

        response.headers["Access-Control-Allow-Credentials"] = 'true'
        response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,GET,POST,PUT,DELETE'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,Token'
        response.headers['Access-Control-Expose-Headers'] = 'VerifyCodeID,ext'
    return response


if __name__ == "__main__":
    manager.run()
